/**
 * @description 用户
 * @author 三咲问道
 * @date 2025/7/14
 */

import { useEffect, useState } from "react";
import styles from "./UsersIndex.module.less";
import { useCartUsersStore } from "@/stores/cartUsersStore";

import { Table, Modal, Form } from "antd";
// import type { TableProps, FormProps } from "antd";
import type { TableColumnsType } from "antd";
import type { CartUsersItem, CartUsersStore } from "@/types/cartUsers.d.ts";

import SearchIndex from "./search/SearchIndex.tsx";
import { ModalIndex } from "./editorModal/ModalIndex.tsx";

function UsersIndex() {
  const {
    usersData,
    getCartUsers,
    createCartUsers,
    updateCartUsers,
    deleteCartUsers,
  } = useCartUsersStore() as CartUsersStore;
  const [searchParams, setSearchParams] = useState({
    name: "",
    nickname: "",
    email: "",
    phone: "",
  });

  /**  重置的状态,用于监听重置 */
  const [resetStatus, setResetStatus] = useState(false);

  /**  表格的类型 */
  interface DataType {
    key: React.Key;
    userId: string;
    name: string;
    nickname: string;
    email: string;
    phone: string;
  }

  const columns: TableColumnsType<DataType> = [
    {
      title: "用户ID",
      dataIndex: "userId",
      key: "userId",
      align: "center",
    },
    {
      title: "用户名",
      dataIndex: "name",
      key: "name",
      align: "center",
    },
    {
      title: "昵称",
      dataIndex: "nickname",
      key: "nickname",
      align: "center",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
      align: "center",
    },
    {
      title: "电话",
      dataIndex: "phone",
      key: "phone",
      align: "center",
    },
    {
      title: "操作",
      dataIndex: "operate",
      key: "operate",
      align: "center",
      render: (_, record) => (
        <div className={styles["operate-content"]}>
          <div className={styles["col-1"]} onClick={() => addHandle()}>
            新增
          </div>
          <div className={styles["col-2"]} onClick={() => deleteHandle(record)}>
            删除
          </div>
          <div className={styles["col-1"]} onClick={() => updateHandle(record)}>
            修改
          </div>
        </div>
      ),
    },
  ];

  useEffect(() => {
    getCartUsersHandle();
  }, []);

  /**  查询 goods 函数 */
  const getCartUsersHandle = (page = { pageCurrent: 1, pageSize: 10 }) => {
    getCartUsers({ ...searchParams, ...page });
  };

  /**  查询 */
  const searchHandle = () => {
    getCartUsersHandle();
  };

  /**  重置 */
  const resetHandle = () => {
    setSearchParams({
      name: "",
      nickname: "",
      email: "",
      phone: "",
    });
    setResetStatus(true);
  };

  useEffect(() => {
    if (resetStatus) {
      getCartUsersHandle();
      setResetStatus(false);
    }
  }, [resetStatus]);

  /**  分页 */
  const pageChange = (pageCurrent: number, pageSize: number) => {
    getCartUsersHandle({ pageCurrent, pageSize });
  };

  const [userOpen, setUserOpen] = useState(false);
  const [basicForm] = Form.useForm();
  const [title, setTitle] = useState<string>("新增");
  const [userId, setUserId] = useState("");

  /**  新增 */
  const addHandle = () => {
    setTitle("新增");
    setUserOpen(true);
  };

  /**  删除 */
  const deleteHandle = (row: CartUsersItem) => {
    console.log("deleteHandle: ", row);
    Modal.confirm({
      title: "删除",
      content: "您是否要删除该数据",
      onOk: async () => {
        const { userId } = row;
        const { code } = deleteCartUsers({ userId });

        // !code && getCartUsersHandle();
        if (code === 0) {
          getCartUsersHandle();
        }
      },
    });
  };

  /**  编辑 */
  const updateHandle = (row: CartUsersItem) => {
    const { userId, name, nickname, email, phone } = row;
    setUserId(userId);
    basicForm.setFieldsValue({ userId, name, nickname, email, phone });
    setTitle("编辑");
    setUserOpen(true);
  };

  /**  确认 */
  const handleOk = async () => {
    setUserOpen(false);
    const formParams = basicForm.getFieldsValue();

    let res = -1;
    /**   编辑 */
    if (userId) {
      const { code } = await updateCartUsers({ ...formParams, userId });
      res = code;
    } else {
      /**  新增 */
      const { code } = await createCartUsers({ ...formParams });
      res = code;
    }

    if (res === 0) {
      handleCancel();
      getCartUsersHandle();
    }
  };

  /**  取消 */
  const handleCancel = () => {
    setUserOpen(false);
    basicForm.setFieldsValue({ name: "", nickname: "", email: "", phone: "" });
    setUserId("");
  };

  return (
    <div className={styles.contain}>
      <SearchIndex
        searchParams={searchParams}
        search={searchHandle}
        reset={resetHandle}
        searchChange={(value) => {
          setSearchParams({ ...searchParams, ...value });
        }}
      />

      <Table<DataType>
        rowKey="userId"
        columns={columns}
        dataSource={usersData.data}
        bordered
        pagination={{
          total: usersData.total,
          current: usersData.pageCurrent,
          pageSize: usersData.pageSize,
          onChange: pageChange,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
      />

      <ModalIndex
        title={title}
        userOpen={userOpen}
        handleOk={handleOk}
        handleCancel={handleCancel}
        basicForm={basicForm}
      />
    </div>
  );
}

export default UsersIndex;
